package com.school.information.utils.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.school.information.utils.baidu.dto.BaiduMapPointDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;

public class BaiDuMapUtil {
    /**
     * 调用百度地图api身份标志
     */
    public static String AK = "VDIElTr8L6bp7TfK92cVAg94qDVR5G2m";

    /**
     * 百度地图 地址和经纬度相互转换api
     */
    public static String URL = "https://api.map.baidu.com/geocoding/v3?";

//    public static void main(String[] args) throws Exception {
//
//        BaiDuMapUtil snCal = new BaiDuMapUtil();
//
//        Map params = new LinkedHashMap<String, String>();
//        params.put("address", "北京市海淀区上地十街10号");
//        params.put("output", "json");
//        params.put("ak", AK);
//        params.put("ret_coordtype", "gcj02ll");
////        params.put("callback", "showLocation");
//
//
//        String result = snCal.requestGetAK(URL, params);
//        JSONObject jsonObject = JSON.parseObject(result);
//        if(jsonObject.getInteger("status") == 0){
//            JSONObject resultObj = jsonObject.getJSONObject("result");
//            JSONObject locationObj = resultObj.getJSONObject("location");
//            System.out.println(locationObj.getDouble("lng"));
//            System.out.println(locationObj.getDouble("lat"));
//        }
//    }

    /**
     * 根据地址返回百度地图的经纬度 坐标 bd09ll
     *
     * @param address
     * @return
     */
    public static BaiduMapPointDTO getPoint(String address) throws Exception {
        BaiduMapPointDTO baiduMapPointDTO = new BaiduMapPointDTO();
        Map params = new LinkedHashMap<String, String>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", AK);
        String result = requestGetAK(URL, params);
        if(StringUtils.isBlank(result)){
            return baiduMapPointDTO;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject.getInteger("status") == 0){
            JSONObject resultObj = jsonObject.getJSONObject("result");
            JSONObject locationObj = resultObj.getJSONObject("location");
            baiduMapPointDTO.setLng(locationObj.getDouble("lng"));
            baiduMapPointDTO.setLat(locationObj.getDouble("lat"));
        }
        return baiduMapPointDTO;
    }

//    public static BaiduMapPointDTO get

    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    private static String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return "";
        }
        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        java.net.URL url = new URL(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();
        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
//        AK: showLocation&&showLocation({"status":0,"result":{"location":{"lng":116.3076223267197,"lat":40.05682848596073},"precise":1,"confidence":80,"comprehension":100,"level":"门址"}})
    }
}